package com.wx.service.imp;

import com.alibaba.dubbo.config.annotation.Service;
import com.wx.constant.MessageConstant;
import com.wx.dao.MemberDao;
import com.wx.dao.OrderDao;
import com.wx.dao.OrdersettingDao;
import com.wx.entity.Result;
import com.wx.pojo.Member;
import com.wx.pojo.Order;
import com.wx.pojo.OrderSetting;
import com.wx.service.OrderService;
import com.wx.utils.DateUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;
import java.util.Map;
@Service(interfaceClass = OrderService.class)
@Transactional
public class OrderServiceImp implements OrderService {

    @Autowired
    private OrdersettingDao ordersettingDao;
    @Autowired
    private MemberDao memberDao;
    @Autowired
    private OrderDao orderDao;

    /**
     * 对传递过来的参数进行校验
     * 对于每个参数都要进行校验
     * @param map
     * @return
     */
    @Override
    public Result addOrder(Map map) {
        // 检查当前日期是否进行了预约设置
        String orderDate = (String) map.get("orderDate");
        try {
            Date date = DateUtils.parseString2Date(orderDate);
            //判断是否已经进行预约设置
            OrderSetting orderByDate = ordersettingDao.findOrderByDate(date);
            if(orderByDate==null){
                return new Result(false,"预约套餐未设置");
            }
            //判断是否已经预约满了
            if(orderByDate.getReservations()>=orderByDate.getNumber()){
                return new Result(false,"预约已满");
            }
            //是否是会员，如果不是进行添加
            String idCard = (String) map.get("idCard");
            Member memberByIdCard = memberDao.findMemberByIdCard(idCard);
            if(memberByIdCard==null){
                //会员未注册
                Member member = new Member();
                //TODO 未封装
                BeanUtils.copyProperties(map,member);
                memberDao.addMember(member);
            }
            // 判断会员是否已经预约
            // 如果memberid与setmealidz在order表中已经存在表示已经预约
            Integer menmberId = memberDao.findMemberByIdCard(idCard).getId();
            String setmealId = (String) map.get("setmealId");
            Order order = new Order();
            order.setSetmealId(Integer.parseInt(setmealId));
            order.setMemberId(menmberId);
            // 进行查询
            org.springframework.core.annotation.Order orderByOrder = orderDao.findOrderByOrder(order);
            if(orderByOrder==null){
                // 有预约添加预约
                return new Result(false,"已经预约");
            }
            // 添加预约，封装为一个实体类
              order.setOrderDate(date);
            orderDao.addOrder(order);
            return new Result(true,"预约成功");

        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false,"预约失败，请重试");
        }
    }
}
